package com.roger.tool.volley;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.protocol.HTTP;

/**
 * @author lch
 * @version Create time：2017-2-15
 * @类说明：
 */
public class HttpUtils {

	public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
	private static final String PARAMETER_SEPARATOR = "&";
	private static final String NAME_VALUE_SEPARATOR = "=";

	public static String format(final Map<String, String> parameters) {
		final StringBuilder result = new StringBuilder();
		if (parameters != null && !parameters.isEmpty()) {
			for (Map.Entry<String, String> entry : parameters.entrySet()) {

				final String encodedKey = encode(entry.getKey(), HTTP.UTF_8);
				final String value = entry.getValue();
				final String encodedValue = value != null ? encode(value, HTTP.UTF_8) : "";

				if (result.length() > 0) {
					result.append(PARAMETER_SEPARATOR);
				}
				result.append(encodedKey);
				result.append(NAME_VALUE_SEPARATOR);
				result.append(encodedValue);
			}
		}

		return result.toString();
	}

	/**
	 * url解码
	 * 
	 * @param content
	 * @param encoding
	 * @return
	 */
	public static String decode(final String content, final String encoding) {
		try {
			return URLDecoder.decode(content, encoding != null ? encoding : HTTP.UTF_8);
		} catch (UnsupportedEncodingException problem) {
			throw new IllegalArgumentException(problem);
		}
	}

	/**
	 * url编码
	 * 
	 * @param content
	 * @param encoding
	 * @return
	 */
	public static String encode(final String content, final String encoding) {
		try {
			return URLEncoder.encode(content, encoding != null ? encoding : HTTP.UTF_8);
		} catch (UnsupportedEncodingException problem) {
			throw new IllegalArgumentException(problem);
		}
	}

}
